﻿using System;
using System.Windows.Controls;
using System.Windows.Input;
using CardPlay.Client.ViewModels;

namespace CardPlay.Client.Tools
{
    public class PeekTool : Tool
    {
        private IDisposable _peekItem;

        public PeekTool(IToolSite host) : base(host)
        {
            State = Inactive;
        }

        private IPlayingContext PlayingContext
        {
            get { return (IPlayingContext)Site.GetService(typeof(IPlayingContext)); }
        }

        private void Inactive(InputEvent inputEvent)
        {
            if (inputEvent.Name != InputEvent.MouseRightButtonDown) return;

            var control = inputEvent.InputElement as Control;
            if (control != null)
            {
                control.Focus();
                //uiElement.Focusable = true;
                //uiElement.Focus();
            }


            var args = (MouseButtonEventArgs)inputEvent.Args;
            var position = args.GetPosition(inputEvent.InputElement);

            var location = PlayingContext.Canvas.HitTest((int)position.X, (int)position.Y);
            if (location.IsUndefined) return;

            CaptureElement = inputEvent.InputElement;
            args.Handled = true;

            _peekItem = PlayingContext.CreatePeekObject(location);

            IsActivated = true;
            State = Peeking;
        }

        private void Peeking(InputEvent inputEvent)
        {
            if (_peekItem == null || IsCancelledBy(inputEvent) || inputEvent.Name == InputEvent.MouseRightButtonUp)
            {
                IsActivated = false;
            }
            else
            {
                var args = inputEvent.Args as MouseButtonEventArgs;
                if (args != null) args.Handled = true;
            }
        }

        protected override void OnDeactivated()
        {
            if (_peekItem != null)
            {
                _peekItem.Dispose();
                _peekItem = null;
            }

            CaptureElement = null;
            State = Inactive;
        }
    }
}